import React, { useState } from "react";
import classNames from 'classnames'
import './index.scss'
import Icon from '../Icon/index'

interface iconProps extends React.HTMLAttributes<HTMLOrSVGElement>{
  className?: string;
  closable?: boolean;
  color?: string;
  visible?: boolean;
  onClose?: Function;
}
const Tag = (props:iconProps) => {
  const {
    className,
    children,
    closable,
    onClose,
    color,
    style:pstyle,
    ...others } = props
  const [visible, setvisible] = useState<boolean>(true)
  
  React.useEffect(() => {
    if ('visible' in props && typeof props.visible!=='undefined') {
      setvisible(props.visible)
    }
  },[props.visible])

  const customColor =color && color?.match(/^#/)
  
  const cls = classNames({
    'ant-tag': true,
    [`ant-tag-${color}`]:color && !customColor,
    [className as string]:!!className
  })

  const style: React.CSSProperties = { ...props.style }
  
  if (customColor) {
   style.backgroundColor=color 
  }
  const handleClick = (e: React.MouseEvent<HTMLElement>) => {
    onClose?.(e)
    console.log(e.defaultPrevented)
    if (e.defaultPrevented) {
      return
    }
    if (!('visible' in props)) {
      setvisible(false)
    }
  }
  if (!visible) {
    return null
  }
  return (
    <span {...others} className={cls} style={style}>
      {children}
      {closable ? <Icon
        type="close"
        size={16}
        style={{ verticalAlign: 'text-top' }}
        onClick={handleClick}
      /> : null}
    </span>
  )
}

export default Tag